const { getUserDataFromRedis } = require("../utils/userRedis");
const { fail, CODE } = require("../utils/utils");

// middleware 中间件
module.exports = (perm) => async (ctx, next) => {
  const { user = {} } = ctx.state;
  try {
    if (!user) {
      return (ctx.body = fail(null, "权限禁止", CODE.AUTH_ERROR));
    }
    const userData = await getUserDataFromRedis(user.user_id);
    if (!userData) {
      return (ctx.body = fail(null, "权限禁止", CODE.AUTH_ERROR));
    }
    //
    const { permissions = [], user_info = {} } = userData;
    // let tokenValidate = false
    // if (user_info && user_info.token) {
    //   let currentToken = ctx.headers.authorization;
    //   currentToken = currentToken.replace("Bearer", "").trim();
    //   if (currentToken === user_info.token) {
    //     tokenValidate = true
    //   }
    // }
    // if (!tokenValidate) {
    //   return (ctx.body = fail(null, "权限禁止", CODE.AUTH_ERROR));
    // }
    if (user_info && user_info.user_type === '00') {
      return next();
    }
    if (perm && permissions.includes(perm)) {
      return next();
    } else {
      ctx.status = 401;
      return (ctx.body = fail(null, "权限禁止", CODE.AUTH_ERROR));
    }
  } catch (error) {
    return (ctx.body = fail(null, error.message, CODE.BUSINESS_ERROR));
  }
};
